import { Component } from '@angular/core';
import { IonicPage, AlertController } from 'ionic-angular';
import { NavController, NavParams, App} from 'ionic-angular';
// import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { UserService } from './services/user.service';

import { LoginPage } from '../login/login';

/**
 * Generated class for the PasswordPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-password',
  templateUrl: 'password.html',
})
export class PasswordPage {

  form: FormGroup;
  id: any;

  constructor(
    private app: App,
    private alertCtrl: AlertController,
    private fb: FormBuilder,
    private service: UserService,
    public navCtrl: NavController, public navParams: NavParams
  ) {
    this.form = this.fb.group({
      originalPassword: [null, [Validators.required]],
      newPassword: [null, [Validators.required]],
      checkPassword: [null, [Validators.required]],
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad PasswordPage');
    this.id = sessionStorage.getItem('token');
    console.log(this.id);
  }


  update() {
    console.log(sessionStorage.getItem('token'));
    console.log(this.form.get('originalPassword'));
    console.log(this.form.get('newPassword'));

    if (this.form.get('newPassword').value === this.form.get('checkPassword').value) {
      // alert("密码一致")
      this.service
        .changePassword(this.id, this.form.get('originalPassword').value, this.form.get('newPassword').value)
        .subscribe(data => {
          console.log(999, data);
          if (data == false) {
            let alert = this.alertCtrl.create({
              title: '提示信息',
              subTitle: '原始密码错误',
              buttons: ['确定']

            })
            alert.present();
            // this.navCtrl.setRoot(LoginPage);

          } else {
            let alert = this.alertCtrl.create({
              title: '提示信息',
              subTitle: '密码设置完成请重新登录',
              buttons: [
                {
                  text: '确定',
                  handler: () => {
                    this.app.getRootNav().setRoot(LoginPage);
                  },
                }
              ]
            })
            alert.present();
          }



        }, err => {
          console.log(err);
        });
    } else {
      let alert = this.alertCtrl.create({
        title: '提示信息',
        subTitle: '新密码请输入一致',
        buttons: ['确定']
      })
      alert.present();
    }

  }

}
